package cn.echogo.framework.http.imp;

import java.io.IOException;

import javax.net.ssl.SSLHandshakeException;

import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;

import android.util.Log;

public class EGHttpRequestRetryHandler implements HttpRequestRetryHandler {

	// 自定义的恢复策略
	public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
		// 设置恢复策略，在Http请求发生异常时候将自动重试3次
		if (executionCount >= 3) {
			// Do not retry if over max retry count
			return false;
		}
		if (exception instanceof NoHttpResponseException) {
			// Retry if the server dropped connection on us
			Log.d("QpidHttpRequestRetryHandler", "Http重连..." + executionCount);
			return true;
		}
		if (exception instanceof SSLHandshakeException) {
			// Do not retry on SSL handshake exception
			return false;
		}
		HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
		boolean idempotent = (request instanceof HttpEntityEnclosingRequest);
		if (!idempotent) {
			// Retry if the request is considered idempotent
			Log.d("QpidHttpRequestRetryHandler", "Http重连..." + executionCount);
			return true;
		}
		return false;
	}

}
